package com.zwps.common.core.mybatis.interceptor;

import java.util.ArrayList;
import java.util.Collection;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.zwps.common.api.model.vo.LoginInfoVO;
import com.zwps.common.core.context.LoginInfoContext;
import com.zwps.common.core.context.LoginedMarkContext;
import com.zwps.common.mybatis.plus.interceptor.CommonDataPermissionInterceptor;
import com.zwps.common.tool.function.FunT0;
import com.zwps.common.tool.function.FunT1;
import com.zwps.common.tool.function.FunT3;

/**
 * 全局范围的数据过滤条件拦截器
 * 
 * @ClassName: GlobalScopeDataInterceptor
 * @Description:
 * @author lyh
 * @date 2023年9月21日 下午8:34:17
 *
 */
public class GlobalScopeDataInterceptor extends CommonDataPermissionInterceptor {

    public static final FunT3<String, String, FunT1<LoginInfoVO, Collection<String>>, Collection<String>> LOGINED_FUN = (
            tableName, columnName, login) -> {
        if (LoginedMarkContext.logined()) {
            Collection<String> vs = login.apply(LoginInfoContext.getLoginInfo());
            if (vs == null) {
                vs = new ArrayList<String>();
                vs.add("nonono!");
//                throw new ServeException("Data permission where in condition table[" + tableName + "] colum["
//                        + columnName + "], list value is null.");
            } else if (vs.isEmpty()) {
                vs.add("nonono!");
//                throw new ServeException("Data permission where in condition table[" + tableName + "] colum["
//                        + columnName + "], list value is empty.");
            }
            return vs;
        }
        return null;
    };

    public GlobalScopeDataInterceptor(MybatisPlusInterceptor mybatisPlusInterceptor) {
        mybatisPlusInterceptor.addInnerInterceptor(this);
    }

    public void addWhereDeptIdIn(String tableName) {
        addWhereIn(tableName, "dept_id", () -> LOGINED_FUN.apply(tableName, "dept_id", (s) -> s.getDataScopeDeptIds()));
    }

    /**
     * 通过获取当前用户信息中的内容添加字符串的查询条件
     * 
     * @Title: addWhereStringInByLoginInfo
     * @Description:
     * @param tableName
     * @param columnName
     * @param val
     * @author lyh
     * @date 2023年9月21日 下午8:27:59
     */
    public void addWhereStringInByLoginInfo(String tableName, String columnName,
            FunT1<LoginInfoVO, Collection<String>> val) {
        addWhereIn(tableName, columnName, () -> LOGINED_FUN.apply(tableName, columnName, val));
    }

    public void addWhereStringIn(String tableName, String columnName, FunT0<Collection<String>> val) {
        addWhereIn(tableName, columnName, val);
    }

    public void addWhereStringEq(String tableName, String columnName, FunT0<String> val) {
        addWhereEq(tableName, columnName, val);
    }
}
